export function stringify (data) {
  if (data && typeof data === 'object') {
    data = JSON.stringify(data)
  }
  return data
}

export function parse (data) {
  try {
    if (typeof data === 'string') {
      data = JSON.parse(data)
    }
  } catch (e) {}
  return data
}

export function clone (data) {
  return JSON.parse(JSON.stringify(data))
}

/**
 * 将平面数据转为树行结构数据
 * @param { Array } data - 数据源
 * @param { String } idField - 唯一标识字符
 * @param { String } parentIdField - 父级标识字符
 * @param { String } nodesField - 生成的子级集合属性字符
 */
export function arrayToTree (data, idField = 'id', parentIdField = 'parent', nodesField = 'children') {
  const nodes = []
  const idHash = {}
  for (let i = 0, l = data.length; i < l; i++) {
    const o = data[i]
    if (!o) {
      continue
    }
    const id = o[idField]
    if (id !== null && id !== undefined) {
      idHash[id] = o
    }
    delete o[nodesField]
  }

  for (var i = 0, l = data.length; i < l; i++) {
    const o = data[i]
    var p = idHash[o[parentIdField]]
    if (!p) {
      nodes.push(o)
      continue
    }
    if (!p[nodesField]) {
      p[nodesField] = []
    }
    p[nodesField].push(o)
  }
  return nodes
}
